//
//  UIImage+RoundedRectImage.m
//  Sky Chat
//
//  Created by XYT on 2021/10/13.
//

#import "UIImage+RoundedRectImage.h"

@implementation UIImage (RoundedRectImage)
- (UIImage *)setRoundedCorners:(CGFloat)radius andSize:(CGSize)size{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
    CGContextAddPath(ctx,path.CGPath);
    CGContextClip(ctx);
    [self drawInRect:rect];
    CGContextDrawPath(ctx, kCGPathFillStroke);
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

//图片置灰操作
+(UIImage *)changeGrayImage:(UIImage *)oldImage{
        CIContext *context = [CIContext contextWithOptions:nil];
        CIImage *superImage = [CIImage imageWithCGImage:oldImage.CGImage];
        CIFilter *lighten = [CIFilter filterWithName:@"CIColorControls"];
        [lighten setValue:superImage forKey:kCIInputImageKey];
 // 修改亮度   -1---1   数越大越亮
        [lighten setValue:@(0) forKey:@"inputBrightness"];
        // 修改饱和度  0---2
        [lighten setValue:@(0) forKey:@"inputSaturation"];
  // 修改对比度  0---4
        [lighten setValue:@(0.5) forKey:@"inputContrast"];
        CIImage *result = [lighten valueForKey:kCIOutputImageKey];
        CGImageRef cgImage = [context createCGImage:result fromRect:[superImage extent]];
        // 得到修改后的图片
        UIImage *newImage =  [UIImage imageWithCGImage:cgImage];
        // 释放对象
        CGImageRelease(cgImage);
    return newImage;
}
- (UIImage *)createGrayCopy:(UIImage *)source{

    int width = source.size.width;

    int height = source.size.height;

    

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

    

    CGContextRef context = CGBitmapContextCreate (nil,

                                                  width,

                                                  height,

                                                  8,      // bits per component

                                                  0,

                                                  colorSpace,

                                                  kCGBitmapByteOrderDefault);

    

    CGColorSpaceRelease(colorSpace);

    

    if (context == NULL) {

        return nil;

    }

    

    CGContextDrawImage(context,

                       CGRectMake(0, 0, width, height), source.CGImage);

    

    UIImage *grayImage = [UIImage imageWithCGImage:CGBitmapContextCreateImage(context)];

    CGContextRelease(context);

    

    return grayImage;

}

@end
